package com.stationbuilding.activity.quality;

import android.Manifest;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Looper;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.SpannedString;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.dmcbig.mediapicker.PickerActivity;
import com.dmcbig.mediapicker.PickerConfig;
import com.dmcbig.mediapicker.entity.Media;
import com.google.gson.Gson;
import com.iceteck.silicompressorr.VideoCompress;
import com.stationbuilding.R;
import com.stationbuilding.activity.SelectActivity;
import com.stationbuilding.adapter.ShowPhotoAdapter;
import com.stationbuilding.api.RetrofitManager;
import com.stationbuilding.bean.ResultBean;
import com.stationbuilding.bean.SelectFileBean;
import com.stationbuilding.constants.Constants;
import com.stationbuilding.dialog.ZoomImageDialog;
import com.stationbuilding.utils.DialogUtils;
import com.stationbuilding.utils.PreferenceHelper;
import com.stationbuilding.utils.StringUtils;
import com.stationbuilding.utils.ZIPUtils;
import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public class QualityAddActivity extends AppCompatActivity implements DatePickerDialog.OnDateSetListener, DialogInterface.OnClickListener {
    private static final int QUESTION_TYPE_ID = 1;
    private static final int QUESTION_LEVEL_ID = 2;
    private static final int DOCUMENT_ID = 3;
    private static final int MODEL = 4;
    private static final int SUBDIVISION_ID = 5;
    private static final int LIABLE_PERSON_ID = 6;
    private static final int SUPERVISOR_ID = 7;
    private static final int ACCEPTOR_ID = 8;
    private static final int CC_PERSON_ID = 9;
    Unbinder unbinder;
    @BindView(R.id.question_name)
    EditText etQuestionName;
    @BindView(R.id.question_type)
    TextView tvQuestionType;
    @BindView(R.id.question_level)
    TextView tvQuestionLevel;
    @BindView(R.id.score)
    EditText etScore;
    @BindView(R.id.question_description)
    EditText etQuestionDescription;
    @BindView(R.id.measures_required)
    EditText etMeasuresRequired;
    @BindView(R.id.photo_or_video)
    ImageView ivPhotoOrVideo;
    @BindView(R.id.modification_date)
    TextView tvModificationDate;
    @BindView(R.id.document)
    TextView tvDocument;
    @BindView(R.id.model)
    TextView tvModel;
    @BindView(R.id.subdivision)
    TextView tvSubdivision;
    @BindView(R.id.liable_person)
    TextView tvLiablePerson;
    @BindView(R.id.supervisor)
    TextView tvSupervisor;
    @BindView(R.id.acceptor)
    TextView tvAcceptor;
    @BindView(R.id.cc_person)
    TextView tvCcPerson;

    private String picPath;//图片存储路径
    private List<SelectFileBean> fileList = new ArrayList<>();
    private Map<String, File> zipMap = new HashMap<>();
    private ShowPhotoAdapter showPhotoAdapter;
    private List<String> showingList = new ArrayList<>();
    private List<String> deleteImageIdList = new ArrayList<>();// 删除照片
    private ArrayList<Media> selected = new ArrayList<>(); // 已选择
    private ArrayList<Media> select;// 本次选择

    private String questionTypeId;
    private String questionLevelId;
    private String modificationDate;
    private String documentId;
    private String subdivisionId;
    private String personLiableIds;
    private String supervisorIds;
    private String acceptorIds;
    private String ccPersonIds;

    private Dialog dialog;//加载提示
    private String token = PreferenceHelper.getInstance(this).getToken();
    private String loginUserId = PreferenceHelper.getInstance(this).getUserId();
    private int zipCount = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_quality_add);
        // 控件绑定
        unbinder = ButterKnife.bind(this);
        // 初始化toolbar
        initToolbar();
        // 初始化图片视频选择
        initPhotoOrVideo();
    }

    private void initToolbar() {
        // 点击事件监听监听
        View.OnClickListener onClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.back:
                        finish();
                        break;
                    case R.id.button:
                        if (checkQuestion()) {
                            saveQuestion();
                        }
                        break;
                }
            }
        };
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        ImageView back = (ImageView) toolbar.findViewById(R.id.back);
        TextView title = (TextView) toolbar.findViewById(R.id.title);
        Button button = (Button) toolbar.findViewById(R.id.button);
        title.setText(getResources().getString(R.string.add_quality));
        button.setText(getResources().getString(R.string.send));
        button.setVisibility(View.VISIBLE);
        back.setOnClickListener(onClickListener);
        button.setOnClickListener(onClickListener);
    }

    private void initPhotoOrVideo() {
        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.photo_video);
        showPhotoAdapter = new ShowPhotoAdapter(this, fileList);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerView.setLayoutManager(manager);
        recyclerView.setAdapter(showPhotoAdapter);
        showPhotoAdapter.setOnLongItemClickListener(new ShowPhotoAdapter.OnItemLongClickListener() {
            @Override
            public void onItemLongClickListener(View view, int position) {
                if (zipMap.size() == zipCount) {
                    showDeleteDialog(position);
                } else {
                    Toast.makeText(QualityAddActivity.this, "视频压缩中，请稍等", Toast.LENGTH_SHORT).show();
                }
            }
        });
        showPhotoAdapter.setOnItemClickListener(new ShowPhotoAdapter.OnItemClickListener() {
            @Override
            public void onItemClickListener(View view, int position) {
                zoomImage(position, fileList);
            }
        });
    }

    @Override
    public void onDestroy() {
        select = null;
        selected = null;
        fileList = null;
        unbinder.unbind();
        Runtime.getRuntime().gc();
        super.onDestroy();
    }

    private boolean checkQuestion() {
        if (TextUtils.isEmpty(etQuestionName.getText().toString())) {
            Toast.makeText(this, "请输入标题", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (TextUtils.isEmpty(questionTypeId)) {
            Toast.makeText(this, "请选择问题类型", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (TextUtils.isEmpty(questionLevelId)) {
            Toast.makeText(this, "请选择问题级别", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (TextUtils.isEmpty(etQuestionDescription.getText().toString()) && (showingList == null || showingList.size() == 0)) {
            Toast.makeText(this, "请输入问题描述或拍摄现场照片或视频", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (TextUtils.isEmpty(modificationDate)) {
            Toast.makeText(this, "请选择截止日期", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (TextUtils.isEmpty(subdivisionId)) {
            Toast.makeText(this, "请选择分部分项", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (TextUtils.isEmpty(personLiableIds)) {
            Toast.makeText(this, "请选择责任人", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (TextUtils.isEmpty(supervisorIds)) {
            Toast.makeText(this, "请选择督办人", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (TextUtils.isEmpty(acceptorIds)) {
            Toast.makeText(this, "请选择验收人", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    /**
     * 保存问题数据
     */
    private void saveQuestion() {
        Gson gson = new Gson();
        Observer<ResultBean> questionBeanSubscriber = new Observer<ResultBean>() {
            @Override
            public void onSubscribe(@io.reactivex.annotations.NonNull Disposable d) {
                dialog = DialogUtils.createLoadingDialog(QualityAddActivity.this, "数据保存中...");
            }
            @Override
            public void onComplete() {
                DialogUtils.closeDialog(dialog);
                setResult(RESULT_OK);
                finish();
            }

            @Override
            public void onError(Throwable e) {
                DialogUtils.closeDialog(dialog);
                Toast.makeText(QualityAddActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onNext(ResultBean resultBean) {
                if (resultBean.getCode() == 0) {
                    Toast.makeText(QualityAddActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(QualityAddActivity.this, resultBean.getMsg(), Toast.LENGTH_SHORT).show();
                }
            }
        };
        MultipartBody.Builder builder = new MultipartBody.Builder();
        // 标题
        builder.addFormDataPart("questionName", etQuestionName.getText().toString());
        // 问题类型
        builder.addFormDataPart("questionType", questionTypeId);
        // 问题等级
        builder.addFormDataPart("questionLevel", questionLevelId);
        // 考核分数
        if (etScore.getText() != null && TextUtils.isEmpty(etScore.getText().toString())) {
            builder.addFormDataPart("score", etScore.getText().toString());
        } else {
            builder.addFormDataPart("score", "0");
        }
        // 问题描述
        builder.addFormDataPart("questionDescription", etQuestionDescription.getText().toString());
        // 措施要求
        builder.addFormDataPart("measuresRequired", etMeasuresRequired.getText().toString());
        // 图片或视频
        for (SelectFileBean selectFileBean : fileList) {
            String path = selectFileBean.getPath();
            if (!path.startsWith(Constants.BASE_URL)) {
                if (selectFileBean.getType() == Constants.PHOTO) {
                    File file = new File(path);
                    RequestBody requestBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);
                    builder.addFormDataPart("beforeImgList", file.getName(), requestBody);
                } else {
                    File zipFile = zipMap.get(path);
                    if (zipFile == null) {
                        Toast.makeText(this, "视频压缩中，请稍等", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    RequestBody requestBody = RequestBody.create(MediaType.parse("application/octet-stream"), zipFile);
                    builder.addFormDataPart("beforeImgList", zipFile.getName(), requestBody);
                }
            }
        }
        // 删除图片id
        if (deleteImageIdList != null && deleteImageIdList.size() > 0) {
            builder.addFormDataPart("deleteImgIdList", gson.toJson(deleteImageIdList));
        }
        // 限改日期
        builder.addFormDataPart("modificationDateStr", tvModificationDate.getText().toString());
        // 资料关联
        builder.addFormDataPart("documentId", documentId);
        // 模型
        // TODO
        // 分部分项
        builder.addFormDataPart("subdivisionId", subdivisionId);
        // 发起人
        builder.addFormDataPart("initiator", loginUserId);
        // 责任人
        if (!StringUtils.isEmpty(personLiableIds)) {
            builder.addFormDataPart("personLiable", personLiableIds);
        }
        // 督办人
        if (!StringUtils.isEmpty(supervisorIds)) {
            builder.addFormDataPart("supervisor", supervisorIds);
        }
        // 验收人
        if (!StringUtils.isEmpty(acceptorIds)) {
            builder.addFormDataPart("acceptor", acceptorIds);
        }
        // 验收人
        if (!StringUtils.isEmpty(ccPersonIds)) {
            builder.addFormDataPart("ccPerson", ccPersonIds);
        }
        // 状态
        builder.addFormDataPart("processStatus", Constants.PROGRESS_STATUS_2);
        // 质量安全标记
        builder.addFormDataPart("safeQualityFlag", String.valueOf(Constants.QUESTION_TYPE_QUALITY));
        // 删除标记
        builder.addFormDataPart("delFlag", Constants.DEL_FLG_0);
        builder.setType(MultipartBody.FORM);
        MultipartBody multipartBody = builder.build();
        RetrofitManager.toSubscribe(RetrofitManager.getApiService().saveQuestion(token, multipartBody), questionBeanSubscriber);
    }

    /**
     * 控件点击事件的处理
     *
     * @param view 控件
     */
    @OnClick({R.id.question_type, R.id.img_question_type, R.id.question_level, R.id.img_question_level, R.id.photo_or_video,
            R.id.modification_date, R.id.img_modification_date, R.id.document, R.id.model, R.id.subdivision, R.id.img_subdivision,
            R.id.liable_person, R.id.img_liable_person, R.id.supervisor, R.id.img_supervisor, R.id.acceptor, R.id.img_acceptor,
            R.id.cc_person, R.id.img_cc_person})
    public void onViewClicked(View view) {
        Intent intent = new Intent(this, SelectActivity.class);
        intent.putExtra("id", view.getId());
        switch (view.getId()) {
            case R.id.question_type:
                intent.putExtra("toolbar_title", getResources().getString(R.string.toolbar_title_question_type));
                startActivityForResult(intent, QUESTION_TYPE_ID);
                break;
            case R.id.question_level:
                intent.putExtra("toolbar_title", getResources().getString(R.string.toolbar_title_question_level));
                startActivityForResult(intent, QUESTION_LEVEL_ID);
                break;
            case R.id.photo_or_video:
                if (zipMap.size() == zipCount) {
                    AlertDialog.Builder alertDialog = new AlertDialog.Builder(this, R.style.Theme_AppCompat_DayNight_Dialog_Alert);
                    alertDialog.setItems(new String[]{"拍摄照片", "拍摄视频", "从相册选择"}, this);
                    alertDialog.show();
                } else {
                    Toast.makeText(QualityAddActivity.this, "视频压缩中，请稍等", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.modification_date:
                final Calendar ca = Calendar.getInstance();
                int year = ca.get(Calendar.YEAR);
                int month = ca.get(Calendar.MONTH);
                int day = ca.get(Calendar.DAY_OF_MONTH);
                DatePickerDialog datePickerDialog = new DatePickerDialog(this, R.style.DatePickerDialogTheme, this, year, month, day);
                DatePicker datePicker = datePickerDialog.getDatePicker();
                datePicker.setMinDate(System.currentTimeMillis());
                datePickerDialog.show();
                break;
            case R.id.document:
                intent.putExtra("toolbar_title", getResources().getString(R.string.toolbar_title_document));
                startActivityForResult(intent, DOCUMENT_ID);
                break;
            case R.id.model:
                intent.putExtra("toolbar_title", getResources().getString(R.string.toolbar_title_model));
                startActivityForResult(intent, MODEL);
                break;
            case R.id.subdivision:
                intent.putExtra("toolbar_title", getResources().getString(R.string.toolbar_title_subdivision));
                startActivityForResult(intent, SUBDIVISION_ID);
                break;
            case R.id.liable_person:
                intent.putExtra("toolbar_title", getResources().getString(R.string.select_contact));
                startActivityForResult(intent, LIABLE_PERSON_ID);
                break;
            case R.id.supervisor:
                intent.putExtra("toolbar_title", getResources().getString(R.string.select_contact));
                startActivityForResult(intent, SUPERVISOR_ID);
                break;
            case R.id.acceptor:
                intent.putExtra("toolbar_title", getResources().getString(R.string.select_contact));
                startActivityForResult(intent, ACCEPTOR_ID);
                break;
            case R.id.cc_person:
                intent.putExtra("toolbar_title", getResources().getString(R.string.select_contact));
                startActivityForResult(intent, CC_PERSON_ID);
                break;
            case R.id.img_question_type:
                changeImage(view.getId(), tvQuestionType, null);
                break;
            case R.id.img_question_level:
                changeImage(view.getId(), tvQuestionLevel, null);
                break;
            case R.id.img_modification_date:
                changeImage(view.getId(), tvModificationDate, null);
                break;
            case R.id.img_subdivision:
                changeImage(view.getId(), tvSubdivision, null);
                break;
            case R.id.img_liable_person:
                changeImage(view.getId(), tvLiablePerson, null);
                break;
            case R.id.img_supervisor:
                changeImage(view.getId(), tvSupervisor, null);
                break;
            case R.id.img_acceptor:
                changeImage(view.getId(), tvAcceptor, null);
                break;
            case R.id.img_cc_person:
                changeImage(view.getId(), tvCcPerson, null);
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK || resultCode == PickerConfig.RESULT_CODE) {
            switch (requestCode) {
                case QUESTION_TYPE_ID:
                    // 问题类型
                    questionTypeId = data.getStringExtra("id");
                    changeImage(R.id.img_question_type, tvQuestionType, data);
                    // 分数
                    AbsoluteSizeSpan absoluteSizeSpan = new AbsoluteSizeSpan(16, true);
                    etScore.getText().clear();
                    etScore.setHint("");
                    int score = data.getIntExtra("score", 999);
                    if (score == 999) {
                        int minValue = data.getIntExtra("minScore", 999);
                        int maxValue = data.getIntExtra("maxScore", 999);
                        if (minValue != 999 && maxValue != 999) {
                            SpannableString scoreStr = new SpannableString(String.valueOf(minValue + "-" + maxValue));
                            scoreStr.setSpan(absoluteSizeSpan, 0, scoreStr.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
                            etScore.setHint(new SpannedString(scoreStr));
                            etScore.setHintTextColor(ContextCompat.getColor(this, R.color.gray_cc));
                        }
                    } else {
                        SpannableString scoreStr = new SpannableString(String.valueOf(score));
                        scoreStr.setSpan(absoluteSizeSpan, 0, scoreStr.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
                        etScore.setText(new SpannedString(scoreStr));
                    }
                    // 措施要求
                    etMeasuresRequired.getText().clear();
                    if (data.getStringExtra("measures") != null) {
                        SpannableString measures = new SpannableString(data.getStringExtra("measures"));
                        measures.setSpan(absoluteSizeSpan, 0, measures.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
                        etMeasuresRequired.setText(new SpannedString(measures));
                    }
                    break;
                case QUESTION_LEVEL_ID:
                    questionLevelId = data.getStringExtra("id");
                    changeImage(R.id.img_question_level, tvQuestionLevel, data);
                    break;
                case SUBDIVISION_ID:
                    subdivisionId = data.getStringExtra("id");
                    changeImage(R.id.img_subdivision, tvSubdivision, data);
                    break;
                case LIABLE_PERSON_ID:
                    personLiableIds = data.getStringExtra("id");
                    changeImage(R.id.img_liable_person, tvLiablePerson, data);
                    break;
                case SUPERVISOR_ID:
                    supervisorIds = data.getStringExtra("id");
                    changeImage(R.id.img_supervisor, tvSupervisor, data);
                    break;
                case ACCEPTOR_ID:
                    acceptorIds = data.getStringExtra("id");
                    changeImage(R.id.img_acceptor, tvAcceptor, data);
                    break;
                case CC_PERSON_ID:
                    ccPersonIds = data.getStringExtra("id");
                    changeImage(R.id.img_cc_person, tvCcPerson, data);
                    break;
                case Constants.PHOTO:
                case Constants.VIDEO:
                    showImage(requestCode);
                    break;
                case Constants.PHOTO_OR_VIDEO:
                    select = data.getParcelableArrayListExtra(PickerConfig.EXTRA_RESULT);
                    showImage(requestCode);
                    break;
            }
        }
    }

    private void changeImage(int id, final TextView textView, Intent data) {
        ImageView imageView = (ImageView) findViewById(id);
        if (data == null) {
            textView.setText(getResources().getString(R.string.please_select));
            textView.setTextColor(ContextCompat.getColor(QualityAddActivity.this, R.color.gray_cc));
            imageView.setImageResource(R.drawable.ic_right);
        } else {
            if (id == R.id.img_liable_person || id == R.id.img_supervisor || id == R.id.img_acceptor || id == R.id.img_cc_person) {
                ArrayList<String> userNameList = data.getStringArrayListExtra("name");
                textView.setText(TextUtils.join(",", userNameList));
            } else {
                textView.setText(data.getStringExtra("name"));
            }
            textView.setTextColor(ContextCompat.getColor(this, R.color.black));
            imageView.setImageResource(R.drawable.ic_delete);
        }
    }

    @Override
    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
        tvModificationDate.setText(year + "-" + (month > 8 ? (month + 1) : "0" + (month + 1)) + "-" + (dayOfMonth > 9 ? dayOfMonth : "0" + dayOfMonth));
        tvModificationDate.setTextColor(ContextCompat.getColor(this, R.color.black));
        ImageView imageView = (ImageView) findViewById(R.id.img_modification_date);
        imageView.setImageResource(R.drawable.ic_delete);
    }

    @Override
    public void onClick(DialogInterface dialog, int which) {
        switch (which) {
            case 0:
                if (checkPermission(Manifest.permission.CAMERA, Constants.PHOTO)) {
                    takePhoto(Constants.PHOTO);
                }
                break;
            case 1:
                if (checkPermission(Manifest.permission.CAMERA, Constants.VIDEO)) {
                    takeVideo(Constants.VIDEO);
                }
                break;
            case 2:
                if (checkPermission(Manifest.permission.READ_EXTERNAL_STORAGE, Constants.PHOTO_OR_VIDEO)) {
                    pickPhotoOrVideo(Constants.PHOTO_OR_VIDEO);
                }
                break;
            default:
                break;
        }
    }

    private boolean checkPermission(String permission, int code) {
        // 件数检查
        if (Manifest.permission.READ_EXTERNAL_STORAGE.equals(permission)) {
            if (showingList.size() == 10 && selected.size() == 0) {
                Toast.makeText(this, "最多只能选择10张图片或视频", Toast.LENGTH_SHORT).show();
                return false;
            }
        } else {
            if (showingList.size() >= 10) {
                Toast.makeText(this, "最多只能选择10张图片或视频", Toast.LENGTH_SHORT).show();
                return false;
            }
        }
        // 权限检查
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED
                    || ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{permission, Manifest.permission.WRITE_EXTERNAL_STORAGE}, code);
                return false;
            } else {
                return true;
            }
        } else {
            return true;
        }
    }

    /**
     * 申请权限的回调，
     *
     * @param requestCode  requestCode
     * @param permissions  permissions
     * @param grantResults grantResults 多个权限一起返回
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (grantResults.length == 2 && grantResults[0] == PackageManager.PERMISSION_GRANTED &&
                grantResults[1] == PackageManager.PERMISSION_GRANTED) {
            if (requestCode == Constants.PHOTO) {
                takePhoto(Constants.PHOTO);
            } else if (requestCode == Constants.VIDEO) {
                takeVideo(Constants.VIDEO);
            } else if (requestCode == Constants.PHOTO_OR_VIDEO) {
                pickPhotoOrVideo(Constants.PHOTO_OR_VIDEO);
            }
        } else {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    /**
     * 调用相机拍照
     */
    private void takePhoto(int type) {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        //获取SD卡的路径
        String sdPath = Environment.getExternalStorageDirectory().getPath();
        picPath = sdPath + "/" + getTime() + ".png";
        Uri uri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            uri = FileProvider.getUriForFile(this, "com.stationbuilding", new File(picPath));
        } else {
            uri = Uri.fromFile(new File(picPath));
        }
        //为拍摄的图片指定一个存储的路径
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        startActivityForResult(intent, type);
    }

    /**
     * 调用相机拍照
     */
    private void takeVideo(int type) {
        Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
        //获取SD卡的路径
        String sdPath = Environment.getExternalStorageDirectory().getPath();
        picPath = sdPath + "/" + getTime() + ".mp4";
        Uri uri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            uri = FileProvider.getUriForFile(this, "com.stationbuilding", new File(picPath));
        } else {
            uri = Uri.fromFile(new File(picPath));
        }
        //为拍摄的视频指定一个存储的路径
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        // 高品质视频
        intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
        // 视频时间限制10秒
        intent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 10);
        startActivityForResult(intent, type);
    }

    /**
     * 从相册选择
     */
    private void pickPhotoOrVideo(int type) {
        Intent intent = new Intent(this, PickerActivity.class);
        // 选择类型为视频和图片
        intent.putExtra(PickerConfig.SELECT_MODE, PickerConfig.PICKER_IMAGE_VIDEO);
        // 文件大小限制
        long maxSize = 188743680L;
        intent.putExtra(PickerConfig.MAX_SELECT_SIZE, maxSize);
        if (type == Constants.PHOTO_OR_VIDEO) {
            // 选择文件数量限制
            intent.putExtra(PickerConfig.MAX_SELECT_COUNT, 10 - showingList.size() + selected.size());
            // 选择文件列表
            intent.putExtra(PickerConfig.DEFAULT_SELECTED_LIST, selected);
        }
        startActivityForResult(intent, type);
    }

    /**
     * 获取时间戳
     */
    public String getTime() {
        long time = System.currentTimeMillis() / 1000;//获取系统时间的10位的时间戳
        return String.valueOf(time);
    }

    /**
     * 压缩图片显示
     */
    private void showImage(int type) {
        RecyclerView photoVideo = (RecyclerView) findViewById(R.id.photo_video);
        photoVideo.setVisibility(View.VISIBLE);
        if (type == Constants.PHOTO) {
            fileList.add(getSelectImageBean(picPath, Constants.PHOTO));
            showingList.add(picPath);
        } else if (type == Constants.VIDEO) {
            compressVideo(picPath, showingList.size(), picPath.substring(picPath.lastIndexOf("/")), Constants.VIDEO);
            fileList.add(getSelectImageBean(picPath, Constants.VIDEO));
            showingList.add(picPath);
        } else if (type == Constants.PHOTO_OR_VIDEO) {
            for (int index = 0; index < selected.size(); index++) {
                boolean containFlg = false;
                for (int selectIndex = 0; selectIndex < select.size(); selectIndex++) {
                    if (select.get(selectIndex).path.equals(selected.get(index).path)) {
                        select.remove(selectIndex);
                        containFlg = true;
                        break;
                    }
                }
                if (!containFlg) {
                    int position = showingList.indexOf(selected.get(index).path);
                    showingList.remove(selected.get(index).path);
                    fileList.remove(position);
                    if (selected.get(index).mediaType != 1) {
                        zipMap.remove(selected.get(index).path);
                        zipCount--;
                    }
                    selected.remove(index);
                    index--;
                }
            }
            for (Media media : select) {
                final String mediaPath = media.path;
                final String mediaName = media.name;
                if (media.mediaType == 1) {
                    fileList.add(getSelectImageBean(mediaPath, Constants.PHOTO));
                } else {
                    fileList.add(getSelectImageBean(mediaPath, Constants.VIDEO));
                    compressVideo(mediaPath, fileList.size() - 1, mediaName, Constants.VIDEO);
                }
                selected.add(media);
                showingList.add(mediaPath);
            }
        }
        if (showingList.size() == 0) {
            photoVideo = (RecyclerView) findViewById(R.id.photo_video);
            photoVideo.setVisibility(View.GONE);
        }
        showPhotoAdapter.setBitmapList(fileList);
        showPhotoAdapter.notifyDataSetChanged();
    }

    /**
     * 是否删除照片的提示框
     */
    private void showDeleteDialog(final int position) {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(this, R.style.AlertDialogTheme);
        alertDialog.setTitle("删除确认");
        alertDialog.setMessage("是否要删除该照片或视频?");
        alertDialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                for (Media media : selected) {
                    if (media.path.equals(showingList.get(position))) {
                        selected.remove(media);
                        if (media.mediaType != 1) {
                            zipMap.remove(media.path);
                            zipCount--;
                        }
                        break;
                    }
                }
                fileList.remove(position);
                showingList.remove(position);
                showPhotoAdapter.setBitmapList(fileList);
                showPhotoAdapter.notifyDataSetChanged();
                if (fileList.size() == 0) {
                    RecyclerView photoVideo = (RecyclerView) findViewById(R.id.photo_video);
                    photoVideo.setVisibility(View.GONE);
                }
            }
        });
        alertDialog.setNegativeButton("关闭", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        });
        // 显示
        alertDialog.show();
    }

    private SelectFileBean getSelectImageBean(String filePath, int type) {
        SelectFileBean selectFileBean = new SelectFileBean();
        selectFileBean.setPath(filePath);
        selectFileBean.setPercent(0);
        selectFileBean.setType(type);
        return selectFileBean;
    }

    private void zoomImage(int position, List<SelectFileBean> list) {
        ZoomImageDialog alertDialog = new ZoomImageDialog(list, position);
        alertDialog.show(getSupportFragmentManager(), "");
    }

    private void compressVideo(final String inPath, final int position, final String fileName, final int type) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Looper.prepare();
                final String outPath = getExternalCacheDir() + inPath.substring(inPath.lastIndexOf("/"));
                final List<File> videoList = new ArrayList<>();
                try {
                    Bitmap videoBitmap = Glide.with(QualityAddActivity.this).load(inPath).asBitmap().centerCrop().into(500, 500).get();
                    videoList.add(ZIPUtils.compressImage(videoBitmap, fileName.substring(0, fileName.lastIndexOf("."))));
                    File file = new File(outPath);
                    if (file.exists()) {
                        file.delete();
                    }
                    file.createNewFile();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                VideoCompress.compressVideoLow(inPath, outPath, new VideoCompress.CompressListener() {
                    @Override
                    public void onStart() {
                        zipCount++;
                    }
                    @Override
                    public void onSuccess() {
                        videoList.add(new File(outPath));
                        File zipFile = new File(QualityAddActivity.this.getCacheDir().getAbsolutePath() + "/" + fileName.substring(0, fileName.lastIndexOf(".") + 1) + "zip");
                        try {
                            if (zipFile.exists()) {
                                zipFile.delete();
                            }
                            zipFile.createNewFile();
                            ZIPUtils.zipFiles(videoList, zipFile);
                            if (type == Constants.VIDEO) {
                                zipMap.put(inPath, zipFile);
                                if (fileList == null) {
                                    return;
                                }
                                fileList.get(position).setLoaded(true);
                                showPhotoAdapter.notifyItemChanged(position, position);
                            }
                        } catch (Exception e) {
                            Toast.makeText(QualityAddActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }
                    @Override
                    public void onFail() {
                        Toast.makeText(QualityAddActivity.this, "失败", Toast.LENGTH_SHORT).show();
                    }
                    @Override
                    public void onProgress(float percent) {
                        if (type == Constants.VIDEO) {
                            if (fileList == null) {
                                return;
                            }
                            fileList.get(position).setPercent(percent);
                            showPhotoAdapter.notifyItemChanged(position, position);
                        }
                    }
                });
                Looper.loop();
            }
        }).start();
    }
}
